package com.biglead.demo.controller;

import com.biglead.demo.common.R;
import com.biglead.demo.pojo.LoginRequest;
import com.biglead.demo.pojo.UserInfo;
import com.biglead.demo.security.JWTGenerator;
import com.biglead.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JWTGenerator jwtGenerator;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public R login(@RequestBody LoginRequest loginDto){
        log.info("登录认证开始 {}",loginDto.toString());
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginDto.getUserName(),
                        loginDto.getPassword()));
        // 认证成功存储认证信息到上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);

        log.info("登录认证完成 {}",loginDto.toString());
        String token = jwtGenerator.generateToken(authentication);
        log.info("登录认证生成 token {}",token);

        String name = authentication.getName();
        //查询用户的详情
        UserInfo userInfo = userService.getByUsername(name);
        //保存用户信息到 redis 中
        ValueOperations<String, UserInfo> operations = redisTemplate.opsForValue();
        //保存用户信息到 redis 中
        operations.set(token, userInfo,7*24*3600, TimeUnit.SECONDS);

        return R.okData(token);
    }

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @PostMapping("register")
    public R register(@RequestBody UserInfo registerDto) {

        registerDto.setPassword(passwordEncoder.encode((registerDto.getPassword())));
        userService.newUser(registerDto);
        return R.ok();
    }
}